﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Dynamic;

namespace DynamicCsvReader
{
    public class DynamicCsvReader
    {
        IContentReader _reader;
        List<dynamic> _items;

        public DynamicCsvReader(StreamReader stream)
        {
            _reader = new StreamContentReader(stream);
        }

        public DynamicCsvReader(string csvContents)
        {
            _reader = new StringContentReader(csvContents);
        }

        private List<dynamic> Decode()
        {
            List<dynamic> items = new List<dynamic>();

            List<string> headers = _reader.ReadLine().Split(',').Select(s => s.Trim()).ToList();

            string str = _reader.ReadLine();

            while (!string.IsNullOrEmpty(str))
            {
                var data = str.Split(',').Select(s => s.Trim()).ToList();

                dynamic obj = new ExpandoObject();

                for (int i = 0; i < headers.Count; i++)
                {
                    ((IDictionary<String, Object>)obj).Add(headers[i], data[i]);
                }

                items.Add(obj);

                str = _reader.ReadLine();
            }

            return items;
        }

        public List<dynamic> Items
        {
            get
            {
                return _items ?? (_items = Decode());
            }
        }
    }
}
